<template>
  <div>
    <el-upload
      v-if="!downloadUrl"
      :data="dataObj"
      :multiple="false"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      class="upload-button"
      :action=baseurl
      accept=".doc,.docx,.xls,.xlsx,.pdf,.ppt,.pptx,.txt,.zip,.rar,.7z"
    >
      <el-button icon="el-icon-upload" size="small" type="primary" plain>点击上传附件</el-button>
    </el-upload>
    <div v-if="downloadUrl" class="download-link-container">
      <el-link :href="downloadUrl" :underline="false">
        <el-button icon="el-icon-download" size="small" type="success" plain>下载</el-button>
      </el-link>
      <el-link :underline="false">
        <el-button icon="el-icon-delete" size="small" type="danger" plain @click="rmFile">删除</el-button>
      </el-link>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'

export default {
  name: 'AttachmentUpload',
  props: ['typ','index'],
  data() {
    return {
      baseurl:process.env.VUE_APP_BASE_URL+"/admin/upload/index",
      downloadUrl: '',
      dataObj: {token: '', fileType: this.typ}
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  methods: {
    rmFile() {
      this.emitInput('')
      this.downloadUrl = ''
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    emitInputIndex(val,index) {
      this.$emit('input', val,index)
    },
    handleUploadSuccess(res) {
      if (res.code == 200) {
        this.downloadUrl = process.env.VUE_APP_BASE_URL + '/admin/Upload/download?tempPath=' + res.data.tempPath

        if(this.index !==null) {
          this.emitInputIndex(res.data, this.index)
        }
        else{
          this.emitInput(res.data)
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    beforeUpload(file) {
      // 可以在这里添加对文件大小、类型等的限制
      // 示例：限制文件大小不超过10MB
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('上传附件大小不能超过 10MB');
        return false;
      }
      this.dataObj.token = this.token;
    },
    resetTempUrl() {
      this.downloadUrl = ''
    },
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  position: relative;
  width: 100%;

  .upload-button {
    display: inline-block;
  }

  .download-link-container {
    margin-top: 20px;
  }
}
</style>
